"""
用户服务
"""

import hashlib
from typing import Optional
from sqlalchemy.orm import Session
from sqlalchemy import and_

from database import User as UserDB
from models.user import User, UserCreate, UserUpdate

class UserService:
    """用户服务类"""
    
    def __init__(self, db: Session):
        self.db = db
    
    def hash_password(self, password: str) -> str:
        """密码哈希"""
        return hashlib.sha256(password.encode()).hexdigest()
    
    def verify_password(self, plain_password: str, hashed_password: str) -> bool:
        """验证密码"""
        return self.hash_password(plain_password) == hashed_password
    
    async def authenticate_user(self, username: str, password: str) -> Optional[User]:
        """用户认证"""
        user = self.db.query(UserDB).filter(
            and_(UserDB.username == username, UserDB.status == 1)
        ).first()
        
        if not user:
            return None
        
        if not self.verify_password(password, user.password_hash):
            return None
        
        return User(
            id=user.id,
            username=user.username,
            name=user.name,
            email=user.email,
            phone=user.phone,
            department=user.department,
            position=user.position,
            avatar=user.avatar,
            status=user.status,
            created_at=user.created_at.isoformat() if user.created_at else None,
            updated_at=user.updated_at.isoformat() if user.updated_at else None
        )
    
    async def get_user_by_id(self, user_id: int) -> Optional[User]:
        """根据ID获取用户"""
        user = self.db.query(UserDB).filter(UserDB.id == user_id).first()
        
        if not user:
            return None
        
        return User(
            id=user.id,
            username=user.username,
            name=user.name,
            email=user.email,
            phone=user.phone,
            department=user.department,
            position=user.position,
            avatar=user.avatar,
            status=user.status,
            created_at=user.created_at.isoformat() if user.created_at else None,
            updated_at=user.updated_at.isoformat() if user.updated_at else None
        )
    
    async def get_user_by_username(self, username: str) -> Optional[User]:
        """根据用户名获取用户"""
        user = self.db.query(UserDB).filter(UserDB.username == username).first()
        
        if not user:
            return None
        
        return User(
            id=user.id,
            username=user.username,
            name=user.name,
            email=user.email,
            phone=user.phone,
            department=user.department,
            position=user.position,
            avatar=user.avatar,
            status=user.status,
            created_at=user.created_at.isoformat() if user.created_at else None,
            updated_at=user.updated_at.isoformat() if user.updated_at else None
        )
    
    async def create_user(self, user_create: UserCreate) -> User:
        """创建用户"""
        # 检查用户名是否已存在
        existing_user = self.db.query(UserDB).filter(UserDB.username == user_create.username).first()
        if existing_user:
            raise ValueError("用户名已存在")
        
        # 创建用户
        db_user = UserDB(
            username=user_create.username,
            password_hash=self.hash_password(user_create.password),
            name=user_create.name,
            email=user_create.email,
            phone=user_create.phone,
            department=user_create.department,
            position=user_create.position,
            avatar=user_create.avatar
        )
        
        self.db.add(db_user)
        self.db.commit()
        self.db.refresh(db_user)
        
        return await self.get_user_by_id(db_user.id)
    
    async def update_user(self, user_id: int, user_update: UserUpdate) -> User:
        """更新用户信息"""
        user = self.db.query(UserDB).filter(UserDB.id == user_id).first()
        if not user:
            raise ValueError("用户不存在")
        
        # 更新字段
        update_data = user_update.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(user, field, value)
        
        self.db.commit()
        self.db.refresh(user)
        
        return await self.get_user_by_id(user_id)
    
    async def get_user_settings(self, user_id: int) -> dict:
        """获取用户设置"""
        settings = self.db.query(UserSettingsDB).filter(UserSettingsDB.user_id == user_id).first()
        
        if not settings:
            # 创建默认设置
            settings = UserSettingsDB(
                user_id=user_id,
                theme="light",
                language="zh-CN",
                notifications_enabled=True,
                auto_login=False
            )
            self.db.add(settings)
            self.db.commit()
            self.db.refresh(settings)
        
        return {
            "theme": settings.theme,
            "language": settings.language,
            "notifications_enabled": settings.notifications_enabled,
            "auto_login": settings.auto_login
        }
    
    async def update_user_settings(self, user_id: int, settings_data: dict) -> dict:
        """更新用户设置"""
        settings = self.db.query(UserSettingsDB).filter(UserSettingsDB.user_id == user_id).first()
        
        if not settings:
            settings = UserSettingsDB(user_id=user_id)
            self.db.add(settings)
        
        # 更新设置
        for field, value in settings_data.items():
            if hasattr(settings, field):
                setattr(settings, field, value)
        
        self.db.commit()
        self.db.refresh(settings)
        
        return await self.get_user_settings(user_id)